<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>学生管理 - 智慧教育考试系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义主题 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#FF9F43',
            neutral: '#F8FAFC',
            'neutral-dark': '#334155',
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .nav-hover {
        @apply transition-all duration-300 hover:bg-primary/10 hover:text-primary;
      }
      .btn-primary {
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 hover:bg-primary/90 active:bg-primary/80;
      }
      .btn-secondary {
        @apply bg-white border border-gray-200 text-neutral-dark px-4 py-2 rounded-lg transition-all duration-300 hover:bg-gray-50 active:bg-gray-100;
      }
      .btn-danger {
        @apply bg-red-50 text-red-600 border border-red-200 px-3 py-1 rounded-lg transition-all duration-300 hover:bg-red-100 active:bg-red-200;
      }
      .btn-edit {
        @apply bg-blue-50 text-blue-600 border border-blue-200 px-3 py-1 rounded-lg transition-all duration-300 hover:bg-blue-100 active:bg-blue-200;
      }
    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-neutral-dark min-h-screen flex flex-col">
  <!-- 顶部导航栏 -->
  <header class="bg-white border-b border-gray-200 sticky top-0 z-30">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-graduation-cap text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-primary">智慧教育考试系统</h1>
      </div>

      <div class="flex items-center space-x-6">
        <div class="hidden md:flex items-center space-x-4">
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-bell-o"></i>
          </button>
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-cog"></i>
          </button>
        </div>

        <div class="flex items-center space-x-2">
          <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa fa-user"></i>
          </div>
          <span class="hidden md:inline">张老师</span>
        </div>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-1 flex flex-col md:flex-row">
    <!-- 左侧导航 -->
    <aside class="w-full md:w-64 bg-white border-r border-gray-200 md:h-[calc(100vh-60px)] sticky md:sticky top-[60px] z-20">
      <!-- 角色切换 -->
      <div class="p-4 border-b border-gray-200">
        <h2 class="text-sm font-medium text-gray-500 mb-2">角色切换</h2>
        <div class="flex rounded-lg overflow-hidden border border-gray-200">
          <button id="teacher-tab" class="flex-1 py-2 px-3 bg-primary text-white text-sm font-medium">
            教师端
          </button>
          <button id="student-tab" class="flex-1 py-2 px-3 bg-white text-gray-600 text-sm font-medium hover:bg-gray-50">
            学生端
          </button>
        </div>
      </div>

      <!-- 教师导航菜单 -->
      <nav id="teacher-nav" class="p-2">
        <ul class="space-y-1">
          <li>
            <a href="/home" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-bar-chart w-5 text-center"></i>
              <span>教师控制台</span>
            </a>
          </li>
          <li>
            <a href="/Publish_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-pencil-square-o w-5 text-center"></i>
              <span>发布考试</span>
            </a>
          </li>
          <li>
            <a href="/History_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-history w-5 text-center"></i>
              <span>历史考试</span>
            </a>
          </li>
          <li>
            <a href="/Set_questions" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-magic w-5 text-center"></i>
              <span>一键出题</span>
            </a>
          </li>
          <li>
            <a href="/Question_Bank" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-book w-5 text-center"></i>
              <span>题库管理</span>
            </a>
          </li>
          <li>
            <a href="/stu_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover text-primary bg-primary/10">
              <i class="fa fa-users w-5 text-center"></i>
              <span>学生管理</span>
            </a>
          </li>
          <li>
            <a href="/class_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-th-large w-5 text-center"></i>
              <span>班级管理</span>
            </a>
          </li>
        </ul>
      </nav>

      <!-- 学生导航菜单 (默认隐藏) -->
      <nav id="student-nav" class="p-2 hidden">
        <ul class="space-y-1">
          <li>
            <a href="/Exam_record" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-file-text-o w-5 text-center"></i>
              <span>个人考试记录</span>
            </a>
          </li>
          <li>
            <a href="/Waiting_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-clock-o w-5 text-center"></i>
              <span>待考试</span>
              <span class="ml-auto bg-accent text-white text-xs px-2 py-0.5 rounded-full">3</span>
            </a>
          </li>
          <li>
            <a href="/Mistake_question" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-exclamation-circle w-5 text-center"></i>
              <span>错题本</span>
            </a>
          </li>

        </ul>
      </nav>
    </aside>

    <!-- 右侧内容区 -->
    <div class="flex-1 p-4 md:p-6 overflow-auto">
      <div class="mb-6">
        <div class="flex items-center">
          <a href="#" class="text-gray-500 hover:text-primary mr-2">
            <i class="fa fa-arrow-left"></i>
          </a>
          <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold">学生管理</h2>
        </div>
        <p class="text-gray-500 mt-1">管理班级学生信息，支持添加、修改和删除操作</p>
      </div>

      <!-- 搜索与添加区域 -->
      <div class="bg-white rounded-xl p-5 card-shadow mb-6">
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div class="relative w-full md:w-96">
            <input id="search-input" type="text" placeholder="搜索学生姓名、学号、班级或账号..."
                  class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
            <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
          </div>

          <div class="flex flex-col sm:flex-row items-center gap-3 w-full md:w-auto">
            <select id="class-filter" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors w-full sm:w-auto">
              <option value="">全部班级</option>
            </select>
            <select id="gender-filter" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors w-full sm:w-auto">
              <option value="">全部性别</option>
            </select>
            <button class="btn-primary flex items-center" id="add_stu">
              <i class="fa fa-plus mr-2"></i> 添加学生
            </button>
          </div>
        </div>
      </div>

      <!-- 学生表格 -->
      <div class="bg-white rounded-xl card-shadow overflow-hidden">
        <div class="overflow-x-auto">
          <table class="w-full min-w-[800px]">
            <thead>
              <tr class="bg-gray-50 text-left">
                <th class="px-6 py-4 text-sm font-medium text-gray-600">
                </th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">学号</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">姓名</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">性别</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">年龄</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">班级</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">账号</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600 text-right">操作</th>
              </tr>
            </thead>
            <tbody id="student-table-body" class="divide-y divide-gray-100">
            </tbody>
          </table>
        </div>
      </div>

      <div id="student-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center px-4 hidden">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-lg p-6">
          <div class="flex items-center justify-between mb-4">
            <h3 id="student-modal-title" class="text-lg font-semibold">添加学生</h3>
            <button id="student-modal-close" class="text-gray-500 hover:text-primary">
              <i class="fa fa-times"></i>
            </button>
          </div>
          <form id="student-form" class="space-y-4">
            <div>
              <label for="student-id-input" class="block text-sm font-medium text-gray-700 mb-1">学号</label>
              <input id="student-id-input" name="student_id" type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" required>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label for="student-name-input" class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                <input id="student-name-input" name="name" type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" required>
              </div>
              <div>
                <label for="student-gender-input" class="block text-sm font-medium text-gray-700 mb-1">性别</label>
                <select id="student-gender-input" name="gender" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
                  <option value="">未设置</option>
                  <option value="男">男</option>
                  <option value="女">女</option>
                </select>
              </div>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label for="student-age-input" class="block text-sm font-medium text-gray-700 mb-1">年龄</label>
                <input id="student-age-input" name="age" type="number" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              </div>
              <div>
                <label for="student-class-input" class="block text-sm font-medium text-gray-700 mb-1">班级</label>
                <input id="student-class-input" name="class_id" type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              </div>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label for="student-account-input" class="block text-sm font-medium text-gray-700 mb-1">账号</label>
                <input id="student-account-input" name="account" type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              </div>
              <div>
                <label for="student-password-input" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                <input id="student-password-input" name="password" type="text" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              </div>
            </div>
            <div class="flex justify-end gap-3 pt-2">
              <button type="button" id="student-modal-cancel" class="btn-secondary">取消</button>
              <button type="submit" class="btn-primary">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </main>

  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 py-4">
    <script>
      const teacherNav = document.getElementById('teacher-nav');
      const studentNav = document.getElementById('student-nav');
      const teacherTab = document.getElementById('teacher-tab');
      const studentTab = document.getElementById('student-tab');

      const setupRoleSwitch = () => {
        teacherTab.addEventListener('click', () => {
          teacherNav.classList.remove('hidden');
          studentNav.classList.add('hidden');
        });
      };

      const setupModeSwitch = () => {
        // ...
      };

      const studentTableBody = document.getElementById('student-table-body');
      const searchInput = document.getElementById('search-input');
      const classFilter = document.getElementById('class-filter');
      const genderFilter = document.getElementById('gender-filter');
      const addStudentButton = document.getElementById('add_stu');
      const studentModal = document.getElementById('student-modal');
      const studentModalTitle = document.getElementById('student-modal-title');
      const studentModalClose = document.getElementById('student-modal-close');
      const studentModalCancel = document.getElementById('student-modal-cancel');
      const studentForm = document.getElementById('student-form');
      const studentIdInput = document.getElementById('student-id-input');
      const studentNameInput = document.getElementById('student-name-input');
      const studentGenderInput = document.getElementById('student-gender-input');
      const studentAgeInput = document.getElementById('student-age-input');
      const studentClassInput = document.getElementById('student-class-input');
      const studentAccountInput = document.getElementById('student-account-input');
      const studentPasswordInput = document.getElementById('student-password-input');

      let currentStudents = [];
      let currentFilters = {
        keyword: '',
        class_id: '',
        gender: ''
      };
      let editingStudentId = null;
      let searchTimer = null;

      const escapeHtml = (value) => {
        if (value === null || value === undefined) {
          return '';
        }
        return String(value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;')
          .replace(/'/g, '&#39;');
      };

      const renderStudents = () => {
        if (!Array.isArray(currentStudents) || !currentStudents.length) {
          studentTableBody.innerHTML = `
            <tr>
              <td colspan="7" class="px-6 py-6 text-center text-gray-500 text-sm">暂无学生数据</td>
            </tr>
          `;
          return;
        }

        studentTableBody.innerHTML = currentStudents.map((student, index) => `
          <tr class="hover:bg-gray-50 transition-colors" data-id="${escapeHtml(student.id)}">
            <td class="px-6 py-4 text-sm text-gray-700">
              <div class="flex items-center">
                <input type="checkbox" class="mr-2">
                ${index + 1}
              </div>
            </td>
            <td class="px-6 py-4 text-sm text-gray-700">${escapeHtml(student.id)}</td>
            <td class="px-6 py-4 text-sm text-gray-700">${escapeHtml(student.name)}</td>
            <td class="px-6 py-4 text-sm text-gray-700">${escapeHtml(student.gender || '')}</td>
            <td class="px-6 py-4 text-sm text-gray-700">${escapeHtml(student.age)}</td>
            <td class="px-6 py-4 text-sm text-gray-700">${escapeHtml(student.class_name || student.class_id || '')}</td>
            <td class="px-6 py-4 text-sm text-gray-700">${escapeHtml(student.account || '')}</td>
            <td class="px-6 py-4 text-right">
              <div class="flex justify-end gap-2">
                <button class="btn-edit text-sm flex items-center" data-action="edit">
                  <i class="fa fa-pencil mr-1"></i> 修改
                </button>
                <button class="btn-danger text-sm flex items-center" data-action="delete">
                  <i class="fa fa-trash mr-1"></i> 删除
                </button>
              </div>
            </td>
          </tr>
        `).join('');
      };

      const populateFilterOptions = (meta) => {
        const { classes = [], genders = [] } = meta || {};

        const existingClassValues = new Set(['']);
        Array.from(classFilter.options).forEach((option) => existingClassValues.add(option.value));
        classes.forEach((cls) => {
          const value = cls.id;
          if (!existingClassValues.has(value)) {
            const option = document.createElement('option');
            option.value = value;
            option.textContent = cls.name;
            classFilter.appendChild(option);
          }
        });

        const existingGenderValues = new Set(['']);
        Array.from(genderFilter.options).forEach((option) => existingGenderValues.add(option.value));
        genders.forEach((gen) => {
          if (!existingGenderValues.has(gen)) {
            const option = document.createElement('option');
            option.value = gen;
            option.textContent = gen;
            genderFilter.appendChild(option);
          }
        });
      };

      const fetchStudents = async () => {
        try {
          const params = new URLSearchParams();
          if (currentFilters.keyword) params.append('keyword', currentFilters.keyword);
          if (currentFilters.class_id) params.append('class_id', currentFilters.class_id);
          if (currentFilters.gender) params.append('gender', currentFilters.gender);

          const response = await fetch(`/api/students${params.toString() ? `?${params.toString()}` : ''}`);
          if (!response.ok) {
            throw new Error('获取学生数据失败');
          }

          const data = await response.json();
          currentStudents = data.students || [];
          populateFilterOptions(data.meta || {});
          renderStudents();
        } catch (error) {
          console.error(error);
          studentTableBody.innerHTML = `
            <tr>
              <td colspan="7" class="px-6 py-6 text-center text-red-500 text-sm">加载失败，请稍后重试</td>
            </tr>
          `;
        }
      };

      const closeStudentModal = () => {
        studentForm.reset();
        studentIdInput.disabled = false;
        editingStudentId = null;
        studentModal.classList.add('hidden');
        document.body.classList.remove('overflow-hidden');
      };

      const openStudentModal = (mode, student = null) => {
        document.body.classList.add('overflow-hidden');
        studentModal.classList.remove('hidden');

        if (mode === 'edit' && student) {
          editingStudentId = student.id;
          studentModalTitle.textContent = '修改学生';
          studentIdInput.value = student.id;
          studentIdInput.disabled = true;
          studentNameInput.value = student.name || '';
          studentGenderInput.value = student.gender || '';
          studentAgeInput.value = student.age ?? '';
          studentClassInput.value = student.class_id || '';
          studentAccountInput.value = student.id || '';
          studentPasswordInput.value = student.password || '';
        } else {
          editingStudentId = null;
          studentModalTitle.textContent = '添加学生';
          studentIdInput.disabled = false;
          studentForm.reset();
        }
      };

      const collectFormPayload = () => {
        const payload = {
          name: studentNameInput.value.trim(),
          gender: studentGenderInput.value,
          age: studentAgeInput.value === '' ? null : studentAgeInput.value,
          class_id: studentClassInput.value.trim(),
          account: studentAccountInput.value.trim(),
          password: studentPasswordInput.value
        };

        if (!editingStudentId) {
          payload.student_id = studentIdInput.value.trim();
        }

        return payload;
      };

      const handleStudentSubmit = async (event) => {
        event.preventDefault();
        const payload = collectFormPayload();

        const method = editingStudentId ? 'PUT' : 'POST';
        const url = editingStudentId ? `/api/students/${encodeURIComponent(editingStudentId)}` : '/api/students';

        try {
          const response = await fetch(url, {
            method,
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
          });

          if (!response.ok) {
            const errorData = await response.json().catch(() => ({ message: '操作失败' }));
            throw new Error(errorData.message || '操作失败');
          }

          await fetchStudents();
          closeStudentModal();
        } catch (error) {
          alert(error.message || '保存失败，请稍后重试');
        }
      };

      const handleDeleteStudent = async (studentId) => {
        if (!studentId) return;
        if (!confirm('确认删除该学生吗？')) return;

        try {
          const response = await fetch(`/api/students/${encodeURIComponent(studentId)}`, {
            method: 'DELETE'
          });
          if (!response.ok) {
            const errorData = await response.json().catch(() => ({ message: '删除失败' }));
            throw new Error(errorData.message || '删除失败');
          }
          await fetchStudents();
        } catch (error) {
          alert(error.message || '删除失败，请稍后重试');
        }
      };

      studentTableBody.addEventListener('click', (event) => {
        const actionButton = event.target.closest('button[data-action]');
        if (!actionButton) return;

        const row = actionButton.closest('tr[data-id]');
        if (!row) return;
        const studentId = row.getAttribute('data-id');
        const student = currentStudents.find((item) => String(item.id) === String(studentId));

        if (actionButton.dataset.action === 'edit') {
          openStudentModal('edit', student);
        }

        if (actionButton.dataset.action === 'delete') {
          handleDeleteStudent(studentId);
        }
      });

      addStudentButton.addEventListener('click', () => {
        openStudentModal('add');
      });

      studentModalClose.addEventListener('click', closeStudentModal);
      studentModalCancel.addEventListener('click', closeStudentModal);

      studentModal.addEventListener('click', (event) => {
        if (event.target === studentModal) {
          closeStudentModal();
        }
      });

      studentForm.addEventListener('submit', handleStudentSubmit);

      searchInput.addEventListener('input', () => {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(() => {
          currentFilters.keyword = searchInput.value.trim();
          fetchStudents();
        }, 300);
      });

      classFilter.addEventListener('change', () => {
        currentFilters.class_id = classFilter.value;
        fetchStudents();
      });

      genderFilter.addEventListener('change', () => {
        currentFilters.gender = genderFilter.value;
        fetchStudents();
      });

      setupRoleSwitch();
      setupModeSwitch();
      fetchStudents();
    </script>
  </footer>
</body>
</html>